﻿@using AntBlazorTableSample.Common
@using AntDesign.TableModels
@typeparam TItem

@inject IHttpClientFactory HttpClientFactory


<Table TItem="TItem"
       PageSize="_pageSize"
       Total="_total"
       DataSource="_dataSource"
       OnChange="OnChangeHandler"
       Loading="_loading"
       PaginationPosition="bottomRight"
       Size="TableSize.Small"
       Responsive>
    <ColumnDefinitions Context="row">
        <FixGenerateColumns Definitions="@((_,c) => { c.Filterable = true; c.Sortable = true; })" />
    </ColumnDefinitions>
</Table>

@code {
    bool _loading;
    int _pageSize = 10;
    int _total;
    List<TItem> _dataSource = [];

    [Parameter] public string HttpClientName { get; set; } = string.Empty;
    [Parameter] public string ServiceEndpoint { get; set; } = string.Empty;

    async Task OnChangeHandler(QueryModel<TItem> query)
    {
        _pageSize = query.PageSize;
        (_total, _dataSource) = await LoadDataAsync(query.PageIndex, query.PageSize);
    }

    protected override async Task OnInitializedAsync()
    {
        (_total, _dataSource) = await LoadDataAsync(1, _pageSize);
        await base.OnInitializedAsync();
    }

    async Task<(int total, List<TItem> data)> LoadDataAsync(int pageNumber, int pageSize)
    {
        try
        {
            _loading = true;
            using var httpClient = HttpClientFactory.CreateClient(HttpClientName);
            var response = await httpClient.GetFromJsonAsync<Paginated<TItem>>($"{ServiceEndpoint}?page={pageNumber}&size={pageSize}");
            return response is not null ? ((int)response.TotalCount, response.Items) : (0, []);
        }
        finally
        {
            _loading = false;
        }
    }
}
